import Cookies from 'js-cookie'
import {
  _findNavTree
} from '@/api/sysadmin/menu'
import {
  constantRoutes
} from '@/router'
/* Layout 第一层菜单需要，路由转发*/
import Layout from '@/layout'

/* SecondView 第二层~倒数第二层需要，路由转发*/
import SecondView from '@/layout/components/SecondView'

/* IFrame*/
import IFrame from '@/components/IFrame'

const tokenKey = 'portal-token'

// 首次加载从cookie获取值
function getFormCookie(key) {
  return Cookies.get(key)
}

// 查找用户可访问的首页
// eslint-disable-next-line no-unused-vars
function getIndex(menuItem) {
  if (menuItem.children !== null && menuItem.children && menuItem.children.length) {
    return getIndex(menuItem.children[0])
  }
  return '/' + menuItem.id
}

let level1Index = -1
// 遍历后台传来的路由字符串，转换为组件对象
// function filterAsyncRouter(asyncMenus) {
//   let array = []
//   asyncMenus.forEach(menuItem => {
//     let route = {
//       name: menuItem.id,
//       path: '/' + menuItem.id,
//       // menuItem.type = 3 隐藏； menuItem.type = 2显示；menuItem.type = 1 后台接口
//       hidden: menuItem.type === 3,
//       meta: {
//         title: menuItem.name,
//         icon: menuItem.icon,
//         hidden: menuItem.type === 3,
//         parentId: menuItem.parentId,
//         parentName: menuItem.parentName
//       }
//     }
//     if (menuItem.level === 1) {
//       route.component = Layout
//       level1Index = level1Index + 1
//     } else if (menuItem.url) {
//       route.meta.url = menuItem.url
//       if (/^iframe#.*/.test(menuItem.url)) {
//         route.component = IFrame
//       } else if (/^href#.*/.test(menuItem.url)) {
//         route.component = Layout
//       } else {
//         route.meta.url = menuItem.url
//         route.component = ((resolve) => require([`@/views${menuItem.url}`], resolve))
//       }
//     } else {
//       route.component = SecondView
//     }
//     // 路由属于第一层菜单的index
//     route.meta.level1Index = level1Index

//     if (menuItem.children !== null && menuItem.children && menuItem.children.length) {
//       route.children = filterAsyncRouter(menuItem.children, level1Index)
//     }
//     array.push(route)
//   })
//   return array
// }

// 接入中软权限
// 遍历后台传来的路由字符串，转换为组件对象
function filterAsyncRouter(asyncMenus) {
  console.log('asyncMenus', asyncMenus)
  const array = []
  asyncMenus.forEach(menuItem => {
    const route = {
      name: menuItem.funcode,
      path: '/' + menuItem.funcode,
      hidden: menuItem.fastFlag === '1',
      meta: {
        title: menuItem.name,
        icon: menuItem.icon,
        hidden: menuItem.fastFlag === '1',
        parentId: menuItem.parentId,
        parentName: menuItem.parentName,
        parentFuncode: menuItem.parentFuncode
      }
    }

    if (menuItem.level === 1) {
      route.component = Layout
      level1Index = level1Index + 1
    } else if (menuItem.path) {
      route.meta.url = menuItem.path
      if (/^iframe#.*/.test(menuItem.path)) {
        route.component = IFrame
      } else if (/^href#.*/.test(menuItem.path)) {
        route.component = Layout
      } else {
        route.meta.url = menuItem.path
        route.component = (resolve) => require([`@/views${menuItem.path}`], resolve)
      }
    } else {
      route.component = SecondView
    }
    // 路由属于第一层菜单的index
    route.meta.level1Index = level1Index

    if (menuItem.menus !== null && menuItem.menus && menuItem.menus.length) {
      route.children = filterAsyncRouter(menuItem.menus, level1Index)
    }
    array.push(route)
    /* if (route.hidden) {
      hiddenRoutes.push(route)
    } else {
      if (menuItem.menus !== null && menuItem.menus && menuItem.menus.length) {
        route.children = filterAsyncRouter(menuItem.menus, level1Index)
      }
      array.push(route)
    } */
  })
  console.log('tree', array)
  return array
}

// 添加导航没有返回的数据
// eslint-disable-next-line no-unused-vars
function processData(menus, addData) {
  let data = menus
  for (var i = 0; i < addData.length; i++) {
    data = processDataItem(data, addData[i])
  }
  return data
}

function processDataItem(menus, addData) {
  // 拿到当前的需要循环的数据和要被加在导航中的数据
  for (var i = 0; i < menus.length; i++) {
    // 如果等于当前的id  我们就加载在当前数据的同级（因为做的一个标签对应多个页面，所以数据格式要这个样子）
    if (menus[i].id === addData.parentId) {
      menus.push(addData)
      // 返回处理过的数据
      return menus
    } else if (menus[i].menus.length > 0) {
      // 如果他有子节点就进行递归循环  返回的是处理过的数据
      menus[i].menus = processDataItem(menus[i].menus, addData)
    }
  }
  // 如果没找到就把整个数据全部返回去
  return menus
}

const user = {
  state: {
    // token: getFormCookie(t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tNHEyTWkyalVzT2FrZFo0U25pWTVOdEwwSnUyMnRSQzJ0Sm4yeWJmK3ZLVE9CQVBEdkdycVNQU1JKNTBnMjhTREtzQnZpNjJxci83QVRHL05ZWE9ad28rNnhlQzYyckV1YWJZUXY4NS9aZ25JRTQ5aGpOQ2xGVTVaUlhGM3RUc3hSKzMyTVVGSElmenR6UEV3YkF3YjRRMWRNU3U2N2tZY1JzMWFDbmJzSkJNZXhUNTBrVWNoL08zTThUQnNEQnZoRFYweEs3Z1FJUGpQejl2OTM0YjdHR0c1NFRwTEEvZjJUdVJvSEZEMUV5Vk45cHFXa1RpaXppSnRNb1RDZVcvR3pSUjk5dFcxb2Y2QVBpZldVekRyWGlnMkYrRFZLNkVNTVVacmMzOEdkajZLaXhSZEI.Vpvp2uNsVuqU4UGZoA__DswrpIFNTZxObg-cvTUHF45xJgdrkUJlgwh-qu1wB4svQb6IUURBbCfARhw0lVssMw',
    refreshTokenKey: 'refreshToken',
    nameCn: getFormCookie('nameCn'),
    deptName: getFormCookie('deptName'),
    deptId: getFormCookie('deptId'),
    topName: '', // 左侧显示最顶层菜单的route.name
    topIcon: '', // 左侧显示最顶层菜单的icon
    topTitle: '', // 左侧显示最顶层菜单的标题
    resources: [], // 左侧显示菜单使用的路由信息数组
    routes: [], // 路由生成后合并的完整路由信息数组
    addRoutes: [], // 后台返回的菜单数据生成的路由信息数组
    menus: [] // 后台返回的菜单数据
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
      Cookies.set(tokenKey, token)
    },
    REMOVE_TOKEN: (state, token) => {
      state.token = ''
      Cookies.remove(tokenKey, token)
    },
    SET_NAMECN: (state, nameCn) => {
      state.nameCn = nameCn
      Cookies.set('nameCn', nameCn)
    },
    SET_DEPTNAME: (state, deptName) => {
      state.deptName = deptName
      Cookies.set('deptName', deptName)
    },
    SET_DEPTID: (state, deptId) => {
      state.deptId = deptId
      Cookies.set('deptId', deptId)
    },
    SET_TOPNAME: (state, topName) => {
      state.topName = topName
    },
    SET_TOPICON: (state, topIcon) => {
      state.topIcon = topIcon
    },
    SET_TOPTITLE: (state, topTitle) => {
      state.topTitle = topTitle
    },
    SET_RESOURCES: (state, resources) => {
      state.resources = resources
    },
    SET_MENUS: (state, menus) => {
      state.menus = menus
    },
    SET_ROUTES: (state, addRoutes) => {
      state.addRoutes = addRoutes
      state.routes = constantRoutes.concat(addRoutes)
    }
  },

  actions: {
    // 生成路由
    GenerateRoutes({
      commit
    }) {
      return new Promise(resolve => {
        // 向后端请求路由数据
        _findNavTree().then(res => {
          if (res.result !== 'success') return
          // 只用于展示-组件-路由
          // commit('SET_MENUS', res.data.menus)

          /* let takeData = [{
            color: "",
            funcode: "navSecond0101",
            id: "navSecond0101",
            isLast: true,
            level: 2,
            menus: [],
            name: "二级导航-1-1",
            openIcon: "fa fa-fw fa-navicon",
            // 不可缺少的  父级id 父级name 父级funcode fastFlag1为隐藏
            parentId: "ecf2459ed6984bbe9ca34d571a327641",
            parentFuncode: "navSecond01",
            fastFlag: "1",
            parentName: "二级导航-1",
            // 不可缺少的 end
            path: "/demo/nav-show/nav-second-01-01.vue",
            visible: true
          }, ] */

          // 处理数据结构，添加返回数据中没有的数据节点（多个页面命中一个节点）
          // let menusData = processData(res.data.menus, takeData)

          // 处理路由导航
          // const accessedRoutes = filterAsyncRouter(menusData)
          const accessedRoutes = filterAsyncRouter(res.data.menus)

          accessedRoutes.push({
            path: '/',
            redirect: accessedRoutes[0].children[0].path,
            hidden: true
          })
          accessedRoutes.push({
            path: '*',
            redirect: '/404',
            hidden: true
          })
          commit('SET_ROUTES', accessedRoutes)
          resolve(accessedRoutes)
        })
      })
    },
    // 前端 登出
    LogOut({
      commit
    }) {
      // web前端清除缓存
      commit('REMOVE_TOKEN')
      /* let cookies = Cookies.get()
      for (let key in cookies) {
        Cookies.remove(key)
      } */
    }
  }
}

export default user
